%------------------------------------------------------------------
%------------------------------------------------------------------
%   Author: Md. Sazzad Hussain (sazzad.hussain@sydney.edu.au)
%   Learning and Affect Technologies Engineering
%   University of Sydney, 2010
%------------------------------------------------------------------
%------------------------------------------------------------------

function [featExt]=iapsFeatEx(subjectID,filesPath,sTime,winSizeECG,winSizeGSR,...
    winSizeEMG,winSizeResp,sRate,dSample,featdir,dubug,opSys)
% %%Sync & Feature Extraction Program (IAPS Physio Data)
%channels: ECG, EMG, GSR, Resp

warning off all;
filesDir=dir(filesPath);%dir info for files path
x=1;
for m=1:length(filesDir)
    [path,name,ext,ver] = fileparts(filesDir(m).name);
    for n=1:length(subjectID(:,1))
        if strncmp(subjectID(n,:),name,27)%choose only selected subjects
            if strcmp(ext,'.mat')%.mat files
                if opSys==1                    
                    loadPhysio(x,:)=[filesPath '/' name ext];%.mat physio path
                elseif opSys==2
                    loadPhysio(x,:)=[filesPath '\' name ext];%.mat physio path
                end
                physioSplit(x,:)= regexp(name,'_','split');
                physioATS=physioSplit(:,5);%physio abs time stamp
%                 x=x+1;
            elseif strcmp(ext, '.txt')%.txt files
                if opSys==1
                    loadAnn(x,:)=[filesPath '/' name ext];%.txt annotation path
                elseif opSys==2
                    loadAnn(x,:)=[filesPath '\' name ext];%.txt annotation path
                end
                x=x+1;
            end
        end
    end
end

mkdir(featdir);%create directory for features (.mat)
for j=1:(x-1)
    load(loadPhysio(j,:));%load physio file

    data=downsample(data,dSample);%-->down sample all physio channels
    nsRate=(sRate/dSample);%new sample rate
    
    fid = fopen(loadAnn(j,:));%load annotation
    C = textscan(fid,'%s%s%s%s%f%s','delimiter', ',');
    fclose(fid);
%     subjectFeatDir=[featdir '\' subjectID(j,:)];
%     mkdir(subjectFeatDir);%create directory for features

    Absolute_Time = datenum(physioATS(j), 'HH-MM-SS')*24*60*60; %in seconds
    
    start_times = C{3};
    k = 2;
    featmat = [];
    featmatECG = [];
    featmatGSR = [];
    featmatEMG = [];
    featmatRESP = [];
    valCatVec=[];
    arCatVec=[];
    dimCatVec=[];
    valSelfVec=[];
    arSelfVec=[];
    dimSelfVec=[];
    
    lenPhysio=length(data);%length of physio data
    %GSR preprocessing
    dataGSR = aubt_lowpassFilter (data(:,2), nsRate, 0.3);
    dataGSR = aubt_scBaseline (dataGSR);
    
    while k <= length (start_times)-1
        Start_Trial = datenum(start_times{k},'HH:MM:SS')*24*60*60; % in seconds
        Start_Index = ((Start_Trial + sTime) - Absolute_Time) * nsRate; %start time
               
        End_IndexECG = (Start_Index + winSizeECG * nsRate)-1;%end time for ecg window
        End_IndexGSR = (Start_Index + winSizeGSR * nsRate)-1;%end time for gsr window
        End_IndexEMG = (Start_Index + winSizeEMG * nsRate)-1;%end time for emg window
        End_IndexResp = (Start_Index + winSizeResp * nsRate)-1;%end time for resp window
        
        if lenPhysio<max([End_IndexECG End_IndexGSR End_IndexEMG End_IndexResp])
            break;
        end
        
        Trial_ChunkECG = data(Start_Index:End_IndexECG,1); %trial chunk
        Trial_ChunkGSR = dataGSR(Start_Index:End_IndexGSR); %trial chunk
        Trial_ChunkEMG1 = data(Start_Index:End_IndexEMG,3); %trial chunk
        Trial_ChunkEMG2 = data(Start_Index:End_IndexEMG,5); %trial chunk
        Trial_ChunkResp = data(Start_Index:End_IndexResp,6); %trial chunk

        if dubug==1
            %plot channels
            pause(0.2)
            subplot(5,1,1),plot(Trial_ChunkECG);
            subplot(5,1,2),plot(Trial_ChunkGSR);
            subplot(5,1,3),plot(Trial_ChunkEMG1);
            subplot(5,1,4),plot(Trial_ChunkEMG2);
            subplot(5,1,5),plot(Trial_ChunkResp);
        end
        
        ecgAffect= Trial_ChunkECG;%ecg data
        gsrAffect= Trial_ChunkGSR;%gsr data
        emg1Affect= Trial_ChunkEMG1;%emg1 data
        emg2Affect= Trial_ChunkEMG2;%emg2 data
        respAffect= Trial_ChunkResp;%resp data
        
        %feature extraction
        [ECGfeatvc ECGfeatnames GSRfeatvc GSRfeatnames EMG1featvc...
            EMG1featnames EMG2featvc EMG2featnames RESPfeatvc...
            RESPfeatnames] = aubtProxy(ecgAffect, gsrAffect, emg1Affect,...
            emg2Affect, respAffect, nsRate);
        
        featvc = [ECGfeatvc,GSRfeatvc,EMG1featvc,EMG2featvc,RESPfeatvc];
        featmat = [featmat;featvc];
%         featvc = [ECGfeatvc,GSRfeatvc,RESPfeatvc];%temp
%         featmat = [featmat;featvc];%temp
        
        %featmat individual for channels
        featvcECG=[ECGfeatvc];
        featmatECG=[featmatECG;featvcECG];
        featvcGSR=[GSRfeatvc];
        featmatGSR=[featmatGSR;featvcGSR];
        featvcEMG=[EMG1featvc, EMG2featvc];
        featmatEMG=[featmatEMG;featvcEMG];
        featvcRESP=[RESPfeatvc];
        featmatRESP=[featmatRESP;featvcRESP];
        
        %extracting theoretical categories
        splitCat=regexp(C{2}(k),'_','split');
        valCat=splitCat{:}(2);
        arCat=splitCat{:}(3);
        dimCat=strcat(valCat,'-',arCat);
        valCatVec = [valCatVec;valCat];
        arCatVec = [arCatVec;arCat];
        dimCatVec = [dimCatVec;dimCat];
        
        %extracting self reports
        switch C{5}(k)
            case 1
                valSelf={'MediumValence'};
                arSelf={'LowArousal'};
                dimSelf={'MediumValence-LowArousal'};
            case 2
                valSelf={'HighValence'};
                arSelf={'LowArousal'};
                dimSelf={'HighValence-LowArousal'};
            case 3
                valSelf={'MediumValence'};
                arSelf={'MediumArousal'};
                dimSelf={'MediumValence-MediumArousal'};
            case 4
                valSelf={'HighValence'};
                arSelf={'MediumArousal'};
                dimSelf={'HighValence-MediumArousal'};
            case 5
                valSelf={'HighValence'};
                arSelf={'HighArousal'};
                dimSelf={'HighValence-HighArousal'};
            case 6
                valSelf={'MediumValence'};
                arSelf={'HighArousal'};
                dimSelf={'MediumValence-HighArousal'};
            case 7
                valSelf={'LowValence'};
                arSelf={'HighArousal'};
                dimSelf={'LowValence-HighArousal'};
            case 8
                valSelf={'LowValence'};
                arSelf={'MediumArousal'};
                dimSelf={'LowValence-MediumArousal'};
            case 9
                valSelf={'LowValence'};
                arSelf={'LowArousal'};
                dimSelf={'LowValence-LowArousal'};
        end
        valSelfVec = [valSelfVec;valSelf];
        arSelfVec = [arSelfVec;arSelf];
        dimSelfVec = [dimSelfVec;dimSelf];
        subjectID(j,:)
        k = k+ 1
    end
    featmat = num2cell(featmat);
    featMatClass = [featmat,dimSelfVec,valSelfVec,arSelfVec,dimCatVec,valCatVec,arCatVec];
    featnames = [ECGfeatnames,GSRfeatnames,strcat(EMG1featnames,'_corr'),strcat(EMG2featnames,'_zym'),RESPfeatnames,...
        'SelfDimension','SelfValence','SelfArousal','CatDimension','CatValence','CatArousal'];    
%     featnames = [ECGfeatnames,GSRfeatnames,RESPfeatnames,...
%         'CatDimension','CatValence','CatArousal', 'SelfDimension','SelfValence','SelfArousal'];%temp    
    
    data_set = [featnames;featMatClass];
    
%     %save all features
%     if opSys==1
%         CELL2CSV([featdir, '\',subjectID(j,:),'_all.csv'],data_set,',');
%     elseif opSys==2
%         CELL2CSV([featdir, '/',subjectID(j,:),'_all.csv'],data_set,',');
%     end
    
    %save for individual channels
    featmatECG = num2cell(featmatECG);
    featmatGSR = num2cell(featmatGSR);
    featmatEMG = num2cell(featmatEMG);
    featmatRESP = num2cell(featmatRESP);
    
    featMatClassECG = [featmatECG,dimSelfVec,valSelfVec,arSelfVec,dimCatVec,valCatVec,arCatVec];
    featMatClassGSR = [featmatGSR,dimSelfVec,valSelfVec,arSelfVec,dimCatVec,valCatVec,arCatVec];
    featMatClassEMG = [featmatEMG,dimSelfVec,valSelfVec,arSelfVec,dimCatVec,valCatVec,arCatVec];
    featMatClassRESP = [featmatRESP,dimSelfVec,valSelfVec,arSelfVec,dimCatVec,valCatVec,arCatVec];
    
    featnamesECG = [ECGfeatnames,'SelfDimension','SelfValence','SelfArousal','CatDimension','CatValence','CatArousal'];
    featnamesGSR = [GSRfeatnames,'SelfDimension','SelfValence','SelfArousal','CatDimension','CatValence','CatArousal'];
    featnamesEMG = [strcat(EMG1featnames,'_corr'),strcat(EMG2featnames,'_zym'),'SelfDimension','SelfValence','SelfArousal','CatDimension','CatValence','CatArousal'];
    featnamesRESP = [RESPfeatnames,'SelfDimension','SelfValence','SelfArousal','CatDimension','CatValence','CatArousal'];
    
    data_setECG = [featnamesECG;featMatClassECG];
    data_setGSR = [featnamesGSR;featMatClassGSR];
    data_setEMG = [featnamesEMG;featMatClassEMG];
    data_setRESP = [featnamesRESP;featMatClassRESP];
    
    if opSys==1        
        ECGDir=[featdir '/ECG_Feat/' num2str(sTime) '-' num2str(winSizeECG)];
        GSRDir=[featdir '/GSR_Feat/' num2str(sTime) '-' num2str(winSizeGSR)];
        EMGDir=[featdir '/EMG_Feat/' num2str(sTime) '-' num2str(winSizeEMG)];
        RespDir=[featdir '/Resp_Feat/' num2str(sTime) '-' num2str(winSizeResp)];
        mkdir(ECGDir);
        mkdir(GSRDir);
        mkdir(EMGDir);
        mkdir(RespDir);        
        
        %save ECG
        CELL2CSV([ECGDir, '/',subjectID(j,:),'_ecg_',num2str(sTime),'-',num2str(winSizeECG),'.csv'],data_setECG,',');
        %saveGSR
        CELL2CSV([GSRDir, '/',subjectID(j,:),'_gsr_',num2str(sTime),'-',num2str(winSizeECG),'.csv'],data_setGSR,',');
        %save EMG
        CELL2CSV([EMGDir, '/',subjectID(j,:),'_emg_',num2str(sTime),'-',num2str(winSizeECG),'.csv'],data_setEMG,',');
        %save Resp
        CELL2CSV([RespDir, '/',subjectID(j,:),'_resp_',num2str(sTime),'-',num2str(winSizeECG),'.csv'],data_setRESP,',');
        
    elseif opSys==2
        ECGDir=[featdir '\ECG_Feat\' num2str(sTime) '_' num2str(winSizeECG)];
        GSRDir=[featdir '\GSR_Feat\' num2str(sTime) '_' num2str(winSizeGSR)];
        EMGDir=[featdir '\EMG_Feat\' num2str(sTime) '_' num2str(winSizeEMG)];
        RespDir=[featdir '\Resp_Feat\' num2str(sTime) '_' num2str(winSizeResp)];
        mkdir(ECGDir);
        mkdir(GSRDir);
        mkdir(EMGDir);
        mkdir(RespDir);
        
        %save ECG
        CELL2CSV([ECGDir, '\',subjectID(j,:),'_ecg_',num2str(sTime),num2str(winSizeECG),'.csv'],data_setECG,',');
        %saveGSR
        CELL2CSV([GSRDir, '\',subjectID(j,:),'_gsr_',num2str(sTime),num2str(winSizeECG),'.csv'],data_setGSR,',');
        %save EMG
        CELL2CSV([EMGDir, '\',subjectID(j,:),'_emg_',num2str(sTime),num2str(winSizeECG),'.csv'],data_setEMG,',');
        %save Resp
        CELL2CSV([RespDir, '\',subjectID(j,:),'_resp_',num2str(sTime),num2str(winSizeECG),'.csv'],data_setRESP,',');
    end
end
clear all;
featExt=1;




